import pymysql
# 导入解析配置文件包
from unit_tools.handle_data.configParse import ConfigParse
from unit_tools.log_utils.recordlog import logs

conf = ConfigParse()


class ConnectMysql:
    """
    连接Mysql数据库，进行增删改查
    """

    def __init__(self):
        self.conf = {
            'host': conf.get_mysql_conf('host'),
            'port': int(conf.get_mysql_conf('port')),
            'user': conf.get_mysql_conf('user'),
            'password': conf.get_mysql_conf('password'),
            'database': conf.get_mysql_conf('database'),
        }
        try:
            self.conn = pymysql.connect(**self.conf)
            # 获取操作游标;cursor=pymysql.cursors.DictCursor将数据库数据以key；value形式显示
            self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
            logs.info(f"成功连接到数据库，数据库ip为：{self.conf.get('host')}")
        except Exception as e:
            logs.error(f"连接数据库失败，原因是：{e}")

    def query(self, sql, fetchall=False):
        """
        查询数据库数据
        :param sql:查询的sql语句
        :param fetchall:查询全部数据，默认为False则查询单条数据
        :return:
        """
        try:
            self.cursor.execute(sql)  # 利用游标执行sql
            self.conn.commit()  # 使用连接提交sql语句
            if fetchall:
                res = self.cursor.fetchall()
            else:
                res = self.cursor.fetchone()
            return res
        except Exception as e:
            logs.error(f"查询数据库内容出现异常：{e}")
        finally:
            self.close()

    def delete(self, sql):
        """
        删除数据库内容
        :param sql:删除的SQL语句
        :return:
        """
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            logs.info("数据库数据删除成功")
        except Exception as e:
            logs.error(f'删除数据库数据出现异常：{e}')
        finally:
            self.close()

    def add(self):
        pass

    def updata(self):
        pass

    def close(self):
        """
        关闭数据库，当连接对象和游标对象存在时
        :return:
        """
        if self.conn and self.cursor:
            self.cursor.close()
            self.conn.close()
            logs.info("成功关闭数据库连接")
        return True


if __name__ == '__main__':
    con = ConnectMysql()
    sql = "SELECT * FROM `variables` WHERE variablesname='吴孙权';"
    res = con.query(sql)
    print(res)
